package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.ProtocolConfigDao;
import cn.wsn2018.tools.dao.ProtocolDesignDao;
import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.Auth;
import cn.wsn2018.tools.model.Config.ProtocolConfig;
import cn.wsn2018.tools.model.Design.ProtocolDesign;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.model.VO.ConfigInfoView;
import cn.wsn2018.tools.model.VO.ProtocolConfigView;
import cn.wsn2018.tools.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by NZX on 2018/12/20.
 */
@Service
public class ProtocolConfigService {
    private static final Logger logger = LoggerFactory.getLogger(ProtocolConfigService.class);
    @Autowired
    private ProtocolConfigDao protocolConfigDao;
    @Autowired
    private ProtocolDesignDao protocolDesignDao;


    @Autowired
    private UserDao userDao;
    /**
     * 新建协议配置
     * @param configInfoView
     * @param myUsername
     * @return
     */
    public String dealProtocolConfigSave(ConfigInfoView configInfoView, String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        ProtocolConfig protocolConfig = new ProtocolConfig();
        if(configInfoView !=null){
            if(configInfoView.getResend()!=null){
                configInfoView.getResend().setTime(Regex.checkReg(configInfoView.getResend().getTime()));
            }
            String designId = configInfoView.getDesignId();
            ProtocolDesign protocolDesign = protocolDesignDao.getProtocolDesign(designId);
            if(protocolDesign!=null){
                protocolConfig.setUsername(protocolDesign.getUsername());
                protocolConfig.setDesignId(designId);
                protocolConfig.setProtocolName(protocolDesign.getProtocolName());
                protocolConfig.setDesignName(protocolDesign.getDesignName());
                //当前时间
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                protocolConfig.setCreateTime(sdf.format(date));
                Auth auth = protocolDesign.getAuth();
                if(auth!=null){
                    protocolConfig.setAuthType(configInfoView.getAuthType());
                }else{
                    protocolConfig.setAuthType("");
                }
                protocolConfig.setEncrypt(configInfoView.getEncrypt());
                protocolConfig.setException(configInfoView.getException());
                protocolConfig.setVirus(configInfoView.getVirus());
                protocolConfig.setResend(configInfoView.getResend());
                protocolConfig.setIntegrity(configInfoView.getIntegrity());
                String id = protocolConfigDao.saveProtocolConfig(protocolConfig);
                if(id!=null){
                    LogUtil.produceLogs(myUsername, CommonValue.CREATE_TYPE,
                            CommonValue.CREATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),
                            CommonValue.LOG_TYPE_BUS,
                            CommonValue.SUCCESS);
                    return JsonUtil.successJson(CommonValue.JSON_INSERT_SUCCESS,null,null);
                }else {

                    LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_CONFIG_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
                }
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_CONFIG_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_CONFIG_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    /**
     * 查询用户的全部协议配置
     * @param username
     * @param pageNum
     * @param pageSize
     * @return
     */
    public String dealProtocolConfigsQuery(String username,String pageNum,String pageSize,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(username!=null&&!username.isEmpty()){
            User user = userDao.getUserByName(username);
            if(user!=null){
                List<ProtocolConfig> configs = protocolConfigDao.getProtocolConfigs(username,pageNum,pageSize);
                LogUtil.produceLogs(username,CommonValue.SELECTED_TYPE,"查询协议配置列表",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                if(configs!=null&&configs.size()!=0){
                    List<ProtocolConfigView> result = new ArrayList<>();
                    for(ProtocolConfig protocolConfig : configs){
                        ProtocolConfigView protocolConfigView = new ProtocolConfigView();
                        protocolConfigView.setId(protocolConfig.getId());
                        protocolConfigView.setUsername(protocolConfig.getUsername());
                        protocolConfigView.setDesignId(protocolConfig.getDesignId());
                        protocolConfigView.setProtocolName(protocolConfig.getProtocolName());
                        protocolConfigView.setDesignName(protocolConfig.getDesignName());
                        protocolConfigView.setCreateTime(protocolConfig.getCreateTime());
                        result.add(protocolConfigView);
                    }
                    JSONArray jsonArray = JSONArray.fromObject(result);
                    return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,null,jsonArray);
                }else {
                    return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
                }
            }else {
                LogUtil.produceLogs(username,CommonValue.SELECTED_TYPE,"查询协议配置列表,但用户名不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }

        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }


    /**
     * 查询某个协议配置
     * @param id
     * @return
     */
    public String dealProtocolConfigQuery(String id, String token, HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(id!=null&&!id.isEmpty()){
            ProtocolConfig protocolConfig = protocolConfigDao.getProtocolConfig(id);
            if(protocolConfig!=null){
                ConfigInfoView configInfoView = new ConfigInfoView();
                configInfoView.setId(protocolConfig.getId());
                configInfoView.setDesignId(protocolConfig.getDesignId());
                configInfoView.setAuthType(protocolConfig.getAuthType());
                configInfoView.setEncrypt(protocolConfig.getEncrypt());
                configInfoView.setException(protocolConfig.getException());
                configInfoView.setResend(protocolConfig.getResend());
                configInfoView.setVirus(protocolConfig.getVirus());
                configInfoView.setIntegrity(protocolConfig.getIntegrity());
                JSONObject jsonObject = JSONObject.fromObject(configInfoView);

                MySessionContext myc= MySessionContext.getInstance();
                HttpSession session = myc.getSession(token);
                String myUsername = session.getAttribute("username").toString();
                LogUtil.produceLogs(myUsername,CommonValue.SELECTED_TYPE,"查询协议设计名为"+protocolConfig.getDesignName()+"对应的协议配置信息",
                        CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
            }else {
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 用designId查询配置
     * @param designId
     * @return
     */
    public String dealProtocolConfigQueryByDesignId(String designId,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(designId!=null&&!designId.isEmpty()){
            ProtocolConfig protocolConfig = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if(protocolConfig!=null){
                ConfigInfoView configInfoView = new ConfigInfoView();
                configInfoView.setId(protocolConfig.getId());
                configInfoView.setDesignId(protocolConfig.getDesignId());
                configInfoView.setAuthType(protocolConfig.getAuthType());
                configInfoView.setEncrypt(protocolConfig.getEncrypt());
                configInfoView.setException(protocolConfig.getException());
                configInfoView.setResend(protocolConfig.getResend());
                configInfoView.setVirus(protocolConfig.getVirus());
                configInfoView.setIntegrity(protocolConfig.getIntegrity());
                JSONObject jsonObject = JSONObject.fromObject(configInfoView);
                return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
            }else {
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 修改用户设计的配置信息
     * @param configInfoView
     * @param myUsername
     * @return
     */
    public String dealProtocolConfigUpdate(ConfigInfoView configInfoView, String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        String designId = configInfoView.getDesignId();
        System.out.println("configInfoView:"+configInfoView);
        if(configInfoView !=null){
            if(configInfoView.getResend()!=null){
                configInfoView.getResend().setTime(Regex.checkReg(configInfoView.getResend().getTime()));
            }
            String id = configInfoView.getId();
            if(id!=null&&!id.isEmpty()){
                ProtocolConfig protocolConfig = protocolConfigDao.getProtocolConfig(id);
                System.out.println("protocolConfig:"+protocolConfig);
                if(protocolConfig!=null){
                    //当前时间
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    protocolConfig.setCreateTime(sdf.format(date));
                    protocolConfig.setEncrypt(configInfoView.getEncrypt());
                    protocolConfig.setException(configInfoView.getException());
                    protocolConfig.setVirus(configInfoView.getVirus());
                    protocolConfig.setResend(configInfoView.getResend());
                    protocolConfig.setIntegrity(configInfoView.getIntegrity());
                    protocolConfig.setAuthType(configInfoView.getAuthType());
                    boolean result = protocolConfigDao.updateProtocolConfig(protocolConfig);

                    if(result){
                        //用户修改配置成功
                        LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,
                                CommonValue.UPDATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),
                                CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);


                        return JsonUtil.successJson(CommonValue.JSON_UPDATE_SUCCESS,null,null);
                    }else {
                        LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),
                                CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                        return JsonUtil.failedJson(CommonValue.JSON_UPDATE_FAILED);
                    }
                }else {
                    LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
                }
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    /**
     * 删除用户的某一协议配置
     * @param id
     * @param myUsername
     * @return
     */
    public String dealProtocolConfigDelete(String id,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        String designId = protocolConfigDao.getProtocolConfig(id).getDesignId();
        if(id!=null&&!id.isEmpty()){
            boolean result = protocolConfigDao.deleteProtocolConfig(id);
            if(result){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS, null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+"，对应的设计id为:D-"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 批量删除协议配置
     * @param idList
     * @param myUsername
     * @return
     */
    public String dealProtocolConfigsDelete(List<String> idList,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        int num = idList.size();
        if(idList!=null&&num!=0){
            int count = protocolConfigDao.deleteProtocolConfigs(idList);
            if(count==num){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS+",计划删除"+num+
                        "条,实际删除"+count+"条",null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED+",计划删除"+num+
                        "条,实际删除"+count+"条");
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_CONFIG_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }
}
